package app.controllers;

import java.text.ParseException;
import java.util.Date;
import java.util.List;

import app.annotations.Public;
import app.models.Consulta;
import app.models.enums.StatusConsulta;
import app.services.ConsultaService;
import app.util.DateUtils;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;

@Resource
public class TaskController extends Controller {

	private Result result;
	private ConsultaService consultaService;
	private static final Long UM_DIA = 86400000l;
	
	public TaskController (Result result, ConsultaService consultaService){
		this.result = result;
		this.consultaService = consultaService;
	}
	
	@SuppressWarnings("deprecation")
	@Public
	@Get("/task/execute")
	public void atualizaStatus(){
		List<Consulta> consultaList = consultaService.findAllForTask();
		Date nowDate = new Date();
		nowDate.setTime(nowDate.getTime() + UM_DIA);
		
		for(Consulta item: consultaList){
			try {
				if(StatusConsulta.PAGA.equals(item.getStatus())){
					if(DateUtils.convertDataStrToDate(item.getData()).getDay() < nowDate.getDay()){
						item.setStatus(StatusConsulta.ATRASADA);
						consultaService.update(item);
					} else {
						if(DateUtils.convertDataStrToDate(item.getData()).getDay() == nowDate.getDay()){
							
							String horaInicial = item.getHoraInicial().replace(":", "");
							
							if(horaInicial.length() == 5){
								horaInicial = "0" + horaInicial;
							}
							if(DateUtils.getHora(horaInicial) < nowDate.getHours() + 1){
								item.setStatus(StatusConsulta.ATRASADA);
								consultaService.update(item);
							}
						}
					}
				}
				
				if(StatusConsulta.MARCADA.equals(item.getStatus())){
					if(DateUtils.convertDataStrToDate(item.getData()).getDay() < nowDate.getDay()){
						item.setStatus(StatusConsulta.PENDENTE);
						consultaService.update(item);
					} else {
						if(DateUtils.convertDataStrToDate(item.getData()).getDay() == nowDate.getDay()){
							String horaInicial = item.getHoraInicial().replace(":", "");
							
							if(horaInicial.length() == 5){
								horaInicial = "0" + horaInicial;
							}
							if(DateUtils.getHora(item.getHoraInicial()) + 1 < nowDate.getHours() + 1){
								item.setStatus(StatusConsulta.PENDENTE);
								consultaService.update(item);
							}
						}
					}
				}
				
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
	}
	
}
